//
//  NiubiModel.m
//  danpin
//
//  Created by chuangjia on 16/11/2015.
//  Copyright © 2015 chuangjia. All rights reserved.
//

#import "NiubiModel.h"
#import "ZShare.h"
#import "SVHTTPRequest.h"
#import "ZHttpCache.h"
#import "NSString+Extensions.h"
#import "ZApi.h"
#import "ZToastManager.h"
@interface NiubiModel ()
{
    
}
@end
static NSString *historyUrl =@"";
@implementation NiubiModel
+(void)cancelRequest
{
    [SVHTTPClient cancelPreviousPerformRequestsWithTarget:self];
}
+ (void)menuListWithParams:(NSDictionary *)params loadCache:(BOOL)cache Block:(void (^)(NSDictionary *,NSInteger, NSError *))block
{
    NSDictionary *userinfo =(NSDictionary*)[ZShare sharedInstance].userInfo;
    NSString *api_key =[[NSString stringWithFormat:@"%@",[ZShare sharedInstance].api_key] replaceNullString];
    NSString *user_name =[[NSString stringWithFormat:@"%@",[userinfo objectForKey:@"nick_name"]] replaceNullString];
    NSString *strURL =[NSString stringWithFormat:@"http://www.mgpyh.com/api/dp/mobilezone/?page__slug=dp&source=dp&api_key=%@&username=%@",api_key,user_name];
    strURL = [strURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    if (cache) {
        id response = [self getBaoliaoDataCache:strURL];
        if (response && [response isKindOfClass:[NSDictionary class]] && [response count]>0) {
            if(block)
                dispatch_async(dispatch_get_main_queue(), ^{
                    block(response,0,nil);
                });
        }
    }
     if([ZApi isConnectionAvailable]==NO)
     {
         [[ZToastManager ShardInstance] showtoast:@"亲，网络不给力哦"];
         if(block)
             dispatch_async(dispatch_get_main_queue(), ^{
                 block(nil,-1,nil);
             });
         return;
     }
    __weak typeof (self) wSelf = self;
    [SVHTTPRequest GET:strURL parameters:nil completion:^(id response, NSHTTPURLResponse *urlResponse, NSError *error)
     {
         if(error)
         {
             if(block)
                 dispatch_async(dispatch_get_main_queue(), ^{
                     block(nil,-1,error);
                 });
             
         }
         NSDictionary *dataDict = (NSDictionary *)response;
         if(dataDict && [dataDict isKindOfClass:[NSDictionary class]]){
             [wSelf SaveBaoliaoArray:dataDict name:strURL];
             if(block)
                 dispatch_async(dispatch_get_main_queue(), ^{
                     block(dataDict,0,nil);
                 });
         }
     }];
}

+ (void)baoliaoListWithParams:(NSDictionary *)params loadCache:(BOOL)cache Block:(void (^)(NSArray *,NSInteger, NSError *))block
{
    NSString *page =[params objectForKey:@"page"];
    NSString *dpzone =[params objectForKey:@"dpzone"];
    NSString *strURL =[NSString stringWithFormat:@"http://dpapi.mgpyh.com/api/v1/get_more/?request_key=dpnew&source=dp&dpzone=%@&page=%@",dpzone,page];
    NSString *requestUrl = [NSString stringWithFormat:@"%@%@",strURL,[ZShare publicParams]];
    requestUrl = [requestUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
   
    if (cache) {
//         NSLog(@"==strURL===使用缓存=cache=\n---%@",strURL);
        id response = [self getBaoliaoDataCache:strURL];
        [self resolveNewestWith:response Block:^(NSArray *newests, NSInteger nextPage, NSError *error) {
            if(block && (newests!=nil && newests.count>0))
                block(newests,nextPage,nil);
        }];
    }

    if([ZApi isConnectionAvailable]==NO)
    {
        [[ZToastManager ShardInstance] showtoast:@"亲，网络不给力哦！"];
        if(block)
            dispatch_async(dispatch_get_main_queue(), ^{
                block(nil,-1,nil);
            });
        return;
    }
    historyUrl = [NSString stringWithFormat:@"%@",requestUrl];
    __weak typeof (self) wSelf = self;
    [SVHTTPRequest GET:requestUrl parameters:nil completion:^(id response, NSHTTPURLResponse *urlResponse, NSError *error)
     {
         if(error || response==nil )
         {
//             NSLog(@"=====网络异常=cache=\n---%@",error);
             if(block)
                 dispatch_async(dispatch_get_main_queue(), ^{
                      block(nil,-1,error);
                 });
             
             return ;
         }
//         NSLog(@"==strURL===网络请求=cache=\n---%@",strURL);
         NSDictionary *resDict = (NSDictionary*)response;
         if (resDict==nil || ![resDict isKindOfClass:[NSDictionary class]]) {
             if(block)
                 dispatch_async(dispatch_get_main_queue(), ^{
                     block(nil,-1,error);
                 });
             
             return ;
         }
         [wSelf resolveNewestWith:response Block:^(NSArray *newests, NSInteger nextPage, NSError *error) {
             //如果获取缓存，就在请求网络回来之后保存数据
             if ([page isEqualToString:@"1"] && (newests!=nil && newests.count>0)) {
                 [wSelf SaveBaoliaoArray:response name:strURL];
             }
             if(block)
                 dispatch_async(dispatch_get_main_queue(), ^{
                    block(newests,nextPage,nil);
                 });
             
         }];
         
     }];
    
}

+(id)getBaoliaoDataCache:(NSString*)strKeyName
{
    id cacheObj = [[ZHttpCache sharedInstance] fetchResponseForUrl:strKeyName byParam:nil];
    return cacheObj;
}
+(void)SaveBaoliaoArray:(id)suggParamsArray name:(NSString*)strKeyName
{
    [[ZHttpCache sharedInstance] storeResponse:suggParamsArray forUrl:strKeyName byParam:nil toDisk:YES];
}
+ (void)resolveNewestWith:(NSDictionary *)dataDict Block:(void (^)(NSArray *newests,NSInteger nextPage, NSError *error))block
{
    if(!dataDict || dataDict.count <=0){
        if(block)
            block(nil,-1,nil);
        return ;
    }
    NSMutableArray *newestList = nil;
    id items = [dataDict objectForKey:@"items"];
    if (items && [items isKindOfClass:[NSArray class]]) {
        newestList = [NSMutableArray arrayWithArray:items];
    }
    NSInteger nextPage = [[dataDict objectForKey:@"nextpage"] intValue];
    if(block)
        block(newestList,nextPage,nil);
}

@end
